/*
 * Relay chat is the javascript file responsible for all the custom scripts running on the 
 * index page for message transfer and room creation. 
 */
var ws;
	
$(document).ready(
		//Gets window location and sets up websocket connection
		function() {
			var url = 'ws://' + window.location.host + '/relaychat/WebSocketChat';   
			ws = new WebSocket( url );
			ws.onopen = function(event) {
				//prompt user to enter name to be used by chat program
				//Stays in loop until user enters something
				var name = '';
				while(name.length < 1){
								name=prompt("Please enter your name.",null);
								if (name || name.length > 0)
								{
									$('#username').val(name);
									$('#message').focus();
								}else
								{
									alert('Please enter a name.');
								}
				}
			}
			ws.onmessage = function(event) {
				//Checks for new room string identifier
				if(event.data.indexOf('##!!') == 0){
					var room = event.data.substring(4,event.data.length);
					//alert(room);
					if($('#'+room).length<1){
						var roomChoice = confirm('Someone just created a new chatroom called:  '+room
								+'.  Do you want to open it?');
						if(roomChoice==true){
							addRoom(room);
						}
					}
					//parses message data and sends string to correct room
				} else{
					var room = event.data.substring(0,event.data.indexOf("-"));
					var message = event.data.substring(event.data.indexOf("-")+1,event.data.length);
					var $textarea = $('#messages'+room);
					$textarea.val($textarea.val() + message + "\n");
					$textarea.animate({
						scrollTop : $textarea.height()
					}, 1000);
					$('#message'+room).focus();
				}
			}
			ws.onclose = function(event) {
				//no implemenation
			}
			
			// Binds keyup function to intial chat tab
			$('.message').keyup(function(e) {
				var keypressed = e.keyCode || event.which;
				if (keypressed == 13) {
					sendMessage('chat');
				}
			});
			
			//binds keyup function to addroom tab
			$('#addRoom').keyup(function(e) {
				var keypressed = e.keyCode || event.which;
				if (keypressed == 13) {
					addRoom($('#addRoomTxt').val());
				}
			});
		}
);
/*
 * sendMessage
 * parameter roomname - text string for assigned room name
 * Sends message via the websocket to all other websocket connections.
 */	
function sendMessage(roomName) {
	var message = roomName +'-'+ $('#username').val() + ":" + $('#message'+roomName).val();
	ws.send(message);
	$('#message'+roomName).val('');
}

//Set up tab functionality via the jquery UI library
$(function() {
    $( "#tabs" ).tabs();
  });

/*
 * addRoom
 * parameter roomName - text string for assigned room name
 * adds room via a local tab by dynamically adding html code to the page.
 */
function addRoom(roomName) {
	$('#addRoomTxt').val('');	
	
	var tabs = $("div#tabs");
	var ul = $("div#tabs ul");
	ul.append(
            "<li><a href='#" + roomName + "'>" + roomName + "</a><span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>"
    );
	//required HTML for new chat room
	tabs.append(
    	'<div id="' + roomName + '" class="chatroom mainChat">' +
			'<div id="menu" class="chatroom chatroomClass">' +
				'<p class="welcome"> Welcome,' + $('#username').val() + '</p>' +
					'<div style="clear: both"></div>'+
			'</div>'+
			'<div id="chatbox">'+
				'<textarea id="messages'+roomName+'" rows="16" cols="48" readonly="readonly"></textarea>'+
			'</div>'+
			'<input name="usermsg" type="text" id="message'+roomName+'" class="message" size="63"  />' +
				'<input type="button" name="submitmsg" value="Send..."'+
				'onclick="sendMessage('+"'"+roomName+"'"+');" />'+
		'</div>' 
        );
        tabs.tabs("refresh");
        //Clicks the tab to ensure focus on the new tab
        $('a[href=#'+roomName+']').click();
        
        //Lets all connection know there is a new room available
        ws.send('##!!'+roomName);
        
        //Binds keyup function to the input box
        $('#message'+roomName).keyup(function(e) {
			var keypressed = e.keyCode || event.which;
			if (keypressed == 13) {
				var message = roomName +'-'+ $('#username').val() + ":" + $('#message'+roomName).val();
	        	ws.send(message);
	        	$('#message'+roomName).val('');
			}
		});
        
        //Adds close functionality to the newly created tab
        tabs.delegate( "span.ui-icon-close", "click", function() {
        	var panelId = $( this ).closest( "li" ).remove().attr( "aria-controls" );
        	$( "#" + panelId ).remove();
        	tabs.tabs( "refresh" );
        	});


}

